/*{
author=pk2.2（风铃等）
version=2.0
date=2023/03/1
}*/


/***
 对辖区内的无人空府进行怀柔,直接获得府的所属权. 

***/

 // ## 2023/05/03 # 铃 # 修复bug,美化显示。 ##
 // ## 2023/05/02 # 铃 # 适配新的内政系统。 ##
 // ## 2023/05/01 # 铃 # 完善了新的怀柔中立府指令的参数。 ##
 // ## 2023/03/01 # 铃 # 新做了自动化内政的怀柔中立府指令。 ##

namespace 怀柔中立府指令
{

	// ================ CUSTOMIZE ================
	// 全局常量 --------------------------------------------------
	/*[text=消耗资金 default=0 min=0 max=5000]*/
	const int gold_num = 0;

	/*[text=消耗行动力 default=50 min=0 max=200]*/
	const int ACTION_COST = 50;

	const bool 小城可设置 = true;
	const bool 调试模式 = false;

	// ===========================================

	const int KEY = pk::hash("怀柔中立府指令");

	class Main
	{

		pk::building @building_;
		pk::force @force_;
		pk::person @kunshu_;
		pk::person @farmer_;
		pk::person @elder_;
		pk::person @officer_;
		pk::person @civilian_;
		pk::city @city_;
		int building_revenue;
		pk::person @actor;
		pk::person @elder;
		int debate_result;
		string target_name;
		pk::building @building_spec;

		Main()
		{

			pk::menu_item 怀柔中立府;
			怀柔中立府.menu = 100;
			怀柔中立府.init = pk::building_menu_item_init_t(init);
			怀柔中立府.is_visible = pk::menu_item_is_visible_t(isMenuVisible_怀柔中立府);
			怀柔中立府.is_enabled = pk::menu_item_is_enabled_t(isEnabled_怀柔中立府);
			怀柔中立府.get_text = pk::menu_item_get_text_t(getText_怀柔中立府);
			怀柔中立府.get_desc = pk::menu_item_get_desc_t(getDesc_怀柔中立府);
			怀柔中立府.handler = pk::menu_item_handler_t(handler_怀柔中立府);
			pk::add_menu_item(怀柔中立府);
		}

		int menu_city_id_;
		int menu_force_id_;
		int base_id;
		int city_id;

		void init(pk::building @building)
		{
			@building_ = @building;
			city_id = pk::get_building_id(building_.pos);
			@city_ = @pk::get_city(city_id);
			@force_ = @pk::get_force(city_.get_force_id());

			@elder = pk::get_person(武将_老翁);
			elder.base_stat[武将能力_智力] = 75 + pk::rand(5);
			elder.update();

			menu_city_id_ = city_.get_id();
			menu_force_id_ = building.get_force_id();
			base_id = building_.get_id();
		}

		int getImageID_1249()
		{
			return 1249;
		}

		bool isMenuVisible_怀柔中立府()
		{

			if (base_id >= 87 || base_id < 0)
				return false;
			else
				return true;
		}

		bool isEnabled_怀柔中立府()
		{

			// pk::trace("able_spec:" + check_怀柔中立府(building)+"  buildingid " +building.get_id());
			if (check_怀柔中立府(building_spec) == 0)
				return true;
			else
				return false;
		}

		int check_怀柔中立府(pk::building @building)
		{
			if (building_ is null or !pk::is_alive(building_))
				return 3;
			if (pk::get_district(building_.get_district_id()).ap < ACTION_COST)
				return 1;
			if (pk::get_gold(building_)< 2000)
				return 5;

			return 0;
		}

		string getText_怀柔中立府()
		{
			return pk::encode("怀柔中立府");
		}

		string getDesc_怀柔中立府()
		{
			int result = check_怀柔中立府(building_spec);
			switch (result)
			{
			case 0:
				return pk::encode(pk::format(" (行动力 {})", ACTION_COST));
			case 1:
				return pk::encode(pk::format("行动力不足 (必须 {} 行动力)", ACTION_COST));
			case 3:
				return pk::encode("无效建筑");
			case 4:
				return pk::encode("无效ID");
			case 5:
				return pk::encode(pk::format("资金至少 (至少 {} )", 2000));
			default:
				return pk::encode("");
			}
			return pk::encode("");
		}

		bool handler_怀柔中立府()
		{

			array<int> spec_arr = get_city_able_spec(city_, force_);
			if (spec_arr.length == 0)
			{
				pk::message_box(pk::encode("没有可怀柔的府."));
				return false;
			}
			int spec_id = choose_spec(spec_arr);
			// 变更府的势力
			if (spec_id == -1)
				return false;
			@building_spec = pk::get_building(ch::get_spec_pos(spec_id));
			target_name = ch::get_spec_name(ch::to_spec_id(building_spec.get_id()));

			// 可执行武将名单
			pk::list<pk::person @> person_list = pk::get_idle_person_list(building_);
			person_list.sort(function(a, b) {
				return a.stat[2] > b.stat[2]; // 按智力排序
			});
			if (person_list.count == 0)
			{
				pk::message_box(pk::encode("没有可用的武将."));
				return false;
			}

			// 执行武将选擇
			if (pk::is_player_controlled(building_))
			{
				pk::list<pk::person @> person_sel = pk::person_selector(pk::encode("武将选择"), pk::encode("选择进行怀柔的武将."), person_list, 1, 1);
				if (person_sel.count == 0)
					return false; // 未选擇时或取消时结束 미선택 시 취소 종료
				@actor = @person_sel[0];
			}
			else
			{
				person_list.sort(function(a, b) {
					return (a.stat[武将能力_智力] > b.stat[武将能力_智力]); // 武将排序(按智力) 무장 정렬 (지력순)
				});
				@actor = @person_list[0];
			}

			int answer_0 = pk::choose({pk::encode(" 是 "), pk::encode(" 否 ")}, pk::encode("是否支付2000金进行怀柔?"), actor);

			if (answer_0 == 0)
			{

				// 支付2000金
				if (pk::get_gold(building_) < 2000)
				{
					pk::message_box(pk::encode("城市金钱不足."));
					return false;
				}

				pk::add_gold(building_, -2000, true);
				pk::scene(pk::scene_t(scene_Event));
			}
			return true;
		}

		void scene_Event()
		{
			pk::background(8);

			pk::message_box(pk::encode(pk::format("当下处于混沌未明的乱世,\x1b[1x{}\x1b[0x若是接受庇护的话.....", target_name)), actor);
			pk::message_box(pk::encode(pk::format("这下可不能装作没听到了!我代表\x1b[1x{}\x1b[0x在此以正视听!", target_name)), pk::get_person(武将_老翁));
			pk::play_se(25);//使用音效
			// 和商人討价还价상인과 흥정
			debate_result = pk::event::debate(actor, elder, pk::is_player_controlled(actor), false, true, true).first; /*发起武将，应战武将，发起方控制与否，应战方控制与否，是否获得经验，是否观看*/

			if (debate_result == 0)
			{
				if (building_spec.get_force_id() != force_.get_id())

				{
					pk::message_box(pk::encode(pk::format("您才是真正的明君啊,\x1b[1x{}\x1b[0x愿意遵从在您的治下!", target_name)), pk::get_person(武将_老翁));
					pk::set_district(building_spec, pk::get_district(building_.get_district_id()), /*점령*/ 0);
					actor.action_done = true;
					actor.update();
					pk::play_bgm(17);
					pk::message_box(pk::encode(pk::format("\x1b[1x{}\x1b[0x已经归顺我军了!", target_name)), actor);
					
				}
			}
			else
			{
				pk::message_box(pk::encode(pk::format("对不起,对\x1b[1x{}\x1b[0x的怀柔失败了.", target_name)), actor);
			}

			pk::background(-1);

		} // scene_Event()

		string get_spec_city_name(int spec_id)
		{
			pk::point pos = ch::get_spec_pos(spec_id);
			int city_id = pk::get_city_id(pos);
			if (city_id == -1)
				return "";
			return pk::decode(pk::get_name(pk::get_city(city_id)));
		}

		int get_spec_id(pk::building @building)
		{
			for (int i = 0; i < ch::get_spec_end(); ++i)
			{
				// pk::trace(pk::format("i {} 数组长度{}", i, ch::get_spec_end()));

				pk::point pos0 = ch::get_spec_pos(i);
				// pk::building@ building0 = pk::get_building(pos0);
				if (building.pos == pos0)
				{
					return i;
				}
			}
			return -1;
		}

		array<int> get_all_spec()
		{
			array<int> temp;
			for (int i = 0; i < ch::get_spec_end(); ++i)
			{
				temp.insertLast(i);
			}
			return temp;
		}

		void scene_舌战怀柔()
		{
			
		}

		pk::list<pk::building @> get_city_able_spec_building(pk::building @building)
		{
			pk::list<pk::building @> temp;
			for (int i = 0; i < ch::get_spec_end(); ++i)
			{
				pk::point pos0 = ch::get_spec_pos(i);
				pk::building @building0 = pk::get_building(pos0);
				if (building0 is null)
					continue;
				// if (building0.get_force_id() == building.get_force_id())
				if (building0.get_force_id() > -1)
					continue;
				auto spec_t = ch::get_spec_p(i);
				if (调试模式)
					pk::trace(pk::format("0 {} {}", get_spec_city_name(i), ch::get_spec_name(i)));
				if (spec_t.person != -1)
					continue;
				int city_id = pk::get_city_id(pos0);
				if (调试模式)
					pk::trace(pk::format("1 {} {}", get_spec_city_name(i), ch::get_spec_name(i)));
				if (building.get_id() != city_id)
					continue;
				if (调试模式)
					pk::trace(pk::format("2 {} {}", get_spec_city_name(i), ch::get_spec_name(i)));
				temp.add(building0); // insertLast(i);
			}
			return temp;
		}

		array<int> get_city_able_spec(pk::city @city, pk::force @force)
		{
			array<int> temp;
			for (int i = 0; i < ch::get_spec_end(); ++i)
			{
				pk::point pos0 = ch::get_spec_pos(i);
				pk::building @building0 = pk::get_building(pos0);
				if (building0 is null)
					continue;
				// if (building0.get_force_id() == force.get_id())
				if (building0.get_force_id() > -1)
					continue;
				auto spec_t = ch::get_spec_p(i);
				if (调试模式)
					pk::trace(pk::format("0 {} {}", get_spec_city_name(i), ch::get_spec_name(i)));
				if (spec_t.person != -1)
					continue;
				int city_id = pk::get_city_id(pos0);
				if (调试模式)
					pk::trace(pk::format("1 {} {}", get_spec_city_name(i), ch::get_spec_name(i)));
				if (city.get_id() != city_id)
					continue;
				if (调试模式)
					pk::trace(pk::format("2 {} {}", get_spec_city_name(i), ch::get_spec_name(i)));
				temp.insertLast(i);
			}
			return temp;
		}

		pk::list<pk::building @> get_able_building(pk::force @force)
		{
			pk::list<pk::building @> temp;
			for (int i = 0; i < ch::get_spec_end(); ++i)
			{
				pk::point pos0 = ch::get_spec_pos(i);
				auto hex = pk::get_hex(pos0);
				if (!hex.has_building)
					continue;
				pk::building @building0 = pk::get_building(pos0);
				if (building0.get_force_id() != force.get_id())
					continue;
				auto spec_t = ch::get_spec_p(i);
				if (spec_t.person != -1)
					continue;
				temp.add(building0);
			}
			return temp;
		}

		pk::list<pk::person @> get_able_person(pk::force @force)
		{
			pk::list<pk::person @> temp;
			pk::list<pk::person @> person_list = pk::get_person_list(force, pk::mibun_flags(身份_都督, 身份_太守, 身份_一般));
			for (int i = 0; i < person_list.count; ++i)
			{
				if (person_list[i].stat[武将能力_统率] > 80 or person_list[i].stat[武将能力_武力] > 80 or person_list[i].stat[武将能力_智力] > 80 or person_list[i].stat[武将能力_政治] > 80 or person_list[i].stat[武将能力_魅力] > 80)
				{
					if (调试模式)
						pk::trace(pk::format("spec_id:{},person_id:{}", ch::get_person_p(person_list[i].get_id()).spec_id, ch::get_person_p(person_list[i].get_id())));
					if (ch::is_valid_spec_id(ch::get_person_p(person_list[i].get_id()).spec_id))
						continue; 
					temp.add(person_list[i]);
					if (调试模式)
						pk::trace(pk::format("势力id：{}，武将：{}，统率：{}，spec_id:{}", force.get_id(), pk::decode(pk::get_name(person_list[i])), person_list[i].stat[武将能力_统率], ch::get_person_p(person_list[i].get_id()).spec_id));
				}
			}
			if (temp.count > 1)
			{
				temp.sort(function(a, b) {
					return a.stat[武将能力_统率] > b.stat[武将能力_统率]; // 按统率排序
				});
			}
			return temp;
		}

		//================================================支持函数================================================//
		int choose_spec(array<int> spec_arr)
		{
			// 一个城市最多8个？
			//  头5+1 中间4+2 尾部 n+1
			int num = int(spec_arr.length);
			int choose_times = (num - 5) / 4; // 除法直接去掉小数
			int mod = (num - 5) % 4;		  // 取余数做末尾
			// 要获取的是spec_id
			array<string> spec_name_list;
			for (int i = 0; i < pk::min(5, num); ++i)
			{
				spec_name_list.insertLast(pk::encode(get_spec_city_name(spec_arr[i]) + ch::get_spec_name(spec_arr[i])));
			}

			if (num == 6)
				spec_name_list.insertLast(pk::encode(get_spec_city_name(spec_arr[num - 1]) + ch::get_spec_name(spec_arr[num - 1])));
			else if (num > 6)
				spec_name_list.insertLast(pk::encode("下一页"));

			int n = pk::choose(pk::encode("请选择府."), spec_name_list);
			if (n == 5 and num != 6)
				return choose_spec_mid(spec_arr, 1);
			return spec_arr[n];
		}

		int choose_spec_mid(array<int> spec_arr, int page)
		{
			// 一个城市最多8个？
			//  头5+1 中间4+2 尾部 n+1
			int num = int(spec_arr.length);
			int num2 = (num - 1 - 4 * page);
			if (num2 <= 5)
			{
				// 最后一页
				// 要获取的是spec_id
				array<string> spec_name_list;
				for (int i = (1 + page * 4); i < (1 + page * 4 + num2); ++i)
				{
					spec_name_list.insertLast(pk::encode(get_spec_city_name(spec_arr[i]) + ch::get_spec_name(spec_arr[i])));
				}
				spec_name_list.insertLast(pk::encode("上一页"));
				int n = pk::choose(pk::encode("请选择府."), spec_name_list);

				if (n == 5 or n == int(spec_name_list.length - 1))
				{
					if (page == 1)
						return choose_spec(spec_arr);
					return choose_spec_mid(spec_arr, page - 1); // 如何返回上一页
				}

				int t = n + (page - 1) * 4 + 5;

				return spec_arr[t];
			}
			else // 不是最后一页
			{
				// 要获取的是spec_id
				array<string> spec_name_list;
				for (int i = (1 + page * 4); i < (1 + page * 4 + 4); ++i)
				{
					spec_name_list.insertLast(pk::encode(get_spec_city_name(spec_arr[i]) + ch::get_spec_name(spec_arr[i])));
				}
				spec_name_list.insertLast(pk::encode("上一页"));
				spec_name_list.insertLast(pk::encode("下一页"));

				int n = pk::choose(pk::encode("请选择府."), spec_name_list);

				// 非最后一页情况
				if (n == 4)
				{
					if (page != 1)
						return choose_spec_mid(spec_arr, page - 1);
					else
						return choose_spec(spec_arr);
				}
				if (n == 5)
					return choose_spec_mid(spec_arr, page + 1);

				int t = n + (page - 1) * 4 + 5;

				return spec_arr[t];
			}
		}

		int 开支级别(pk::building @building)
		{
			int base_id = building_.get_id();
			int level = ch::get_city_level(base_id);
			if (level == 0)
				return 500;
			else if (level == 1)
				return 800;
			else if (level == 2)
				return 1000;
			else if (level == 3)
				return 1200;
			else if (level == 4)
				return 1500;
			else
				return 500;
		}

		string numberpad_t(int line, int original_value, int current_value)
		{
			return pk::encode("");
		}

	}

	Main main;
}